package com.yl.order.ui.fragment;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.device.DeviceApiRepository;
import com.net.device.entity.PostOrderEntity;
import com.net.device.entity.PostOrderGoodsEntity;
import com.yl.common.ui.BaseFragment;
import com.yl.common.utils.LogUtil;
import com.yl.order.App;
import com.yl.order.R;
import com.yl.order.db.entity.OrderEntity;
import com.yl.order.db.entity.OrderGoodsEntity;
import com.yl.order.entity.PrintOrderGoodsEntity;
import com.yl.order.helper.SmallApkHelper;
import com.yl.order.model.OrderModel;
import com.yl.order.ui.adapter.BaseEmptyAdapter;
import com.yl.order.ui.component.LinearDividerItemDecoration;
import com.yl.order.ui.dialog.PayFragment;
import com.yl.order.utils.OrderUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * create by cjx on 2024/6/8
 * desc:
 */
public class ShopCartFragment extends BaseFragment implements View.OnClickListener {

    TextView totalView;
    TextView payView;
    ShopCartAdapter adapter;

    public static ShopCartFragment newInstance() {
        return new ShopCartFragment();
    }

    @Override
    public int getViewId() {
        return R.layout.fragment_shop_cart;
    }

    @Override
    public void afterViewShow() {
        totalView = findViewById(R.id.total);
        payView = findViewById(R.id.pay);

        @SuppressLint("NotifyDataSetChanged")
        View.OnClickListener listener = v -> {
            int id = v.getId();
            if (id == R.id.clear) {
                clear();
            } else {
                pay();
            }
        };

        findViewById(R.id.clear).setOnClickListener(listener);
        payView.setEnabled(false);
        payView.setOnClickListener(listener);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setItemAnimator(null);
        recyclerView.addItemDecoration(new LinearDividerItemDecoration(LinearLayoutManager.VERTICAL,
                getResources().getDimensionPixelSize(R.dimen.dp_1), ContextCompat.getColor(getContext(), R.color.main_bg)));
        adapter = new ShopCartAdapter(new ArrayList<>(), this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        OrderGoodsEntity entity = (OrderGoodsEntity) v.getTag();
        int index = adapter.getList().indexOf(entity);
        if (id == R.id.add) {
            entity.setQuantity(entity.getQuantity() + 1);
            adapter.notifyItemChanged(index);
        } else if (id == R.id.reduce) {
            if (entity.getQuantity() == 1) {
//                adapter.list.remove(index);
//                adapter.notifyItemRemoved(index);
            } else {
                entity.setQuantity(entity.getQuantity() - 1);
                adapter.notifyItemChanged(index);
            }
        } else {
            adapter.getList().remove(index);
            adapter.notifyItemRemoved(index);
        }
        refreshTotal();
    }

    public void addGoods(OrderGoodsEntity entity) {
        OrderGoodsEntity orderGoods = null;
        for (OrderGoodsEntity g : adapter.getList()) {
            if (g.getGoodsNumber().equals(entity.getGoodsNumber()) && g.getSpecName().equals(entity.getSpecName())) {
                orderGoods = g;
                break;
            }
        }
        if (orderGoods == null) {
            adapter.getList().add(entity);
            adapter.notifyItemInserted(adapter.getList().size());
        } else {
            orderGoods.setQuantity(orderGoods.getQuantity() + 1);
            adapter.notifyItemChanged(adapter.getList().indexOf(orderGoods));
        }
        refreshTotal();
    }

    private void refreshTotal() {
        int total = 0;
        for (OrderGoodsEntity g : adapter.getList()) {
            total += g.getQuantity();
        }
        if (total == 0) {
            totalView.setText(null);
            payView.setEnabled(false);
            payView.setText(R.string.button_pay);
            payView.setTag(null);
        } else {
            totalView.setText(String.format(getString(R.string.order_total_format), total));
            payView.setEnabled(true);
            BigDecimal bigDecimal = new BigDecimal("0");
            for (OrderGoodsEntity entity : adapter.getList()) {
                bigDecimal = bigDecimal.add(new BigDecimal(entity.getPrice())
                        .multiply(new BigDecimal(entity.getQuantity())));
            }
            String price = bigDecimal.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
            payView.setText(String.format(getString(R.string.order_pay_format), price));
            payView.setTag(price);
        }
    }

    private void pay() {
        String price = (String) payView.getTag();

        OrderEntity order = OrderUtils.buildOrderEntity(price);
        ArrayList<OrderGoodsEntity> orderGoods = OrderUtils.buildOrderDetail(order, adapter.getList());
        if (price == null || Float.parseFloat(price) == 0) {
            paySuccess(order, orderGoods);
        } else {
            PayFragment.newInstance(price, order, orderGoods)
                    .setPayCallback(i -> {
                        paySuccess(order, orderGoods);
                    })
                    .show(getFragmentManager(), "pay");
        }
    }

    private void paySuccess(OrderEntity order, ArrayList<OrderGoodsEntity> orderGoods) {
        order.setSerialNo(App.app.serialNumber++);
        print(order, orderGoods);
        post(order, orderGoods);
        OrderModel.saveOrder(order, orderGoods);
        clear();
    }

    private void print(OrderEntity order, ArrayList<OrderGoodsEntity> orderGoods) {
        ArrayList<PrintOrderGoodsEntity> pogList = new ArrayList<>(orderGoods.size());
        for (OrderGoodsEntity goods : orderGoods) {
            PrintOrderGoodsEntity pog = new PrintOrderGoodsEntity(goods.getOrderNo() + "," + goods.getOrderSubNo(),
                    goods.getGoodsName(), goods.getSpecName(), goods.getPrice());
            pogList.add(pog);
        }
        // 打印订单标签
        HashMap<String, Object> printMap = new HashMap<>(2);
        printMap.put("serialNumber", order.getSerialNo());
        printMap.put("time", order.getCreateTime());
        printMap.put("goodsList", pogList);
        String json = new Gson().toJson(printMap);
        LogUtil.getInstance().log("打印订单", "发送信息：" + json);
        SmallApkHelper.printService(2, new Gson().toJson(printMap));
    }

    private void post(OrderEntity order, ArrayList<OrderGoodsEntity> orderGoods) {
        ArrayList<PostOrderGoodsEntity> orderDetails = new ArrayList<>();
        for (OrderGoodsEntity goods : orderGoods) {
            PostOrderGoodsEntity pog = new PostOrderGoodsEntity(goods.getProductNumber(), goods.getGoodsName(),
                    Integer.parseInt(goods.getOrderSubNo()));
            orderDetails.add(pog);
        }
        PostOrderEntity po = new PostOrderEntity(order.getOrderNo(), order.getCreateTime(), order.getOriginName(), null,
                orderDetails);
        DeviceApiRepository.getInstance().postOrder(po, response -> {
            if (response == null) {
                showToast("推送失败！");
                return;
            }
            if (!response.isSuccess()) {
                showToast(response.getMessage());
            }
        }, error -> {
            showToast("推送失败： " + error.getMessage());
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void clear() {
        adapter.clear();
        refreshTotal();
    }

    private static class ShopCartAdapter extends BaseEmptyAdapter<OrderGoodsEntity> {

        View.OnClickListener listener;

        public ShopCartAdapter(ArrayList<OrderGoodsEntity> list, View.OnClickListener listener) {
            super(list);
            this.listener = listener;
        }

        @Override
        public void onBindItemHolder(RecyclerView.ViewHolder viewHolder, int i) {
            ViewHolder ho = (ViewHolder) viewHolder;
            OrderGoodsEntity item = list.get(i);
            ho.nameView.setText(item.getGoodsName());
            ho.specView.setText(item.getSpecName());
            ho.quantityView.setText(String.valueOf(item.getQuantity()));
            ho.priceView.setText(String.format(App.app.getString(R.string.order_price_format), item.getPrice()));
            ho.addView.setTag(item);
            ho.reduceView.setTag(item);
            ho.deleteView.setTag(item);
        }

        @Override
        public RecyclerView.ViewHolder createItemViewHolder(ViewGroup parent, int i) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_shop_cart, parent, false);
            ViewHolder viewHolder = new ViewHolder(v);
            viewHolder.addView.setOnClickListener(listener);
            viewHolder.reduceView.setOnClickListener(listener);
            viewHolder.deleteView.setOnClickListener(listener);
            return viewHolder;
        }

        public void clear() {
            this.list.clear();
        }

        public ArrayList<OrderGoodsEntity> getList() {
            return this.list;
        }
    }

    private static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameView;
        TextView specView;
        TextView priceView;
        TextView quantityView;
        ImageView addView;
        ImageView reduceView;
        ImageView deleteView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            nameView = itemView.findViewById(R.id.name);
            specView = itemView.findViewById(R.id.spec);
            priceView = itemView.findViewById(R.id.price);
            quantityView = itemView.findViewById(R.id.quantity);
            addView = itemView.findViewById(R.id.add);
            reduceView = itemView.findViewById(R.id.reduce);
            deleteView = itemView.findViewById(R.id.delete);
        }
    }
}
